// createHooks.ts
import React, { createElement } from 'react';
import { createRoot } from 'react-dom/client';

interface ModalInstance {
  destroy: () => void;
  update: (props: any) => void;
}

export const createHooks = <T extends Record<string, any> = {}>(
  ModalComponent: React.ComponentType<any>
) => {
  const showModal = (props?: T): ModalInstance => {
    const container = document.createElement('div');
    document.body.appendChild(container);

    let currentProps = { ...props, open: true };
    const root = createRoot(container);

    const destroy = () => {
      root.unmount();
      if (container.parentNode) {
        container.parentNode.removeChild(container);
      }
    };

    const update = (newProps: any) => {
      currentProps = { ...currentProps, ...newProps };
      render(currentProps);
    };

    const render = (props: any) => {
      const element = createElement(ModalComponent, {
        ...props,
        // 不覆盖组件的事件处理，只提供 close 函数
        close: destroy,
      });

      root.render(element);
    };

    render(currentProps);

    return {
      destroy,
      update,
    };
  };

  return showModal;
};